import { getApi } from "./http";
import Message from 'tdesign-miniprogram/message/index';
import { currentAccount, loginWxampForWechatCallback } from "../service/api/api-login";
import access from "./access";

export const request = <T = any>(url: string, params: any) => {
  return new Promise<T>((resolve, reject) => {
    const app = getApp();
    wx.request<T>({
      url: getApi() + url,
      header: {
        satoken: app.globalData.satoken
      },
      ...params,
      success: (result) => {
        if (result && result.statusCode == 200) {
          //一定要先判断status==200再接收值，这是小程序的规则决定的。
          const { code, msg } = result.data as T
          if (code == 0) {
            resolve(result.data as T)
          } else if (code == 50 || code == 13) {
            //用户登录过期，重新登录
            //用户在其他地方切换了单位，需要重新登录
            wx.login({
              success: res => {
                loginWxampForWechatCallback({ serviceName: "xtbs", code: res.code }).then(response => {
                  if (response.code === 0) {

                    const { satoken } = response.data;

                    let app = getApp();

                    app.globalData.satoken = satoken;

                    currentAccount().then(responseCurrentUser => {
                      if (responseCurrentUser.code == 0) {

                        app.globalData.access = access(responseCurrentUser.data);
                        app.globalData.currentUser = responseCurrentUser.data;
                        wx.setStorageSync('currentUser', responseCurrentUser.data);// 存到缓存

                        wx.reLaunch({
                          url: '/pages/home/index'
                        })
                      }
                    });
                  }

                })
              },
            })
            return reject(msg);
          } else {
            Message.error({
              context: this,
              offset: [20, 32],
              duration: 5000,
              content: result.data.msg,
              closeBtn: true,
            });
            // wx.showToast({
            //   icon: 'error',
            //   title: result.data.msg
            // })
            reject(result.data.msg || '获取失败'); //响应失败就执行reject()
          }
        } else {

          let pages = getCurrentPages()
          let currentPage = pages[pages.length - 1]
          // console.log("===============", currentPage) //此为当前页面

          if (currentPage.route === 'pages/devops/index') {

          } else {
            wx.reLaunch({
              url: '/pages/devops/index'
            })
          }
          reject(result.data.msg || '获取失败'); //响应失败就执行reject()
        }
      }, fail: (err) => {
        reject(err)
      }, complete: function (res) {
      }
    })
  })
}